package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.activities.NewDigestActivity;
import me.shurufa.adapter.ShelvesBookAdapter;
import me.shurufa.implement.BookLongClickListener;
import me.shurufa.model.Book;
import me.shurufa.model.BookListResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.colordialog.ColorDialog;
import me.shurufa.widget.popupwindow.ShelvesFavouriteWindow;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.recyclerview.HeaderSpanSizeLookup;

/**
 * 书架Fragment
 *
 * @FileName: me.shurufa.activities.BookShelvesFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-18 10:52
 */
public class BookShelvesFragment extends BaseListFragment implements View.OnClickListener, BookLongClickListener {

    @Bind(R.id.left_text)
    TextView leftText;
    @Bind(R.id.right_image)
    ImageView rightImage;
    @Bind(R.id.right_text)
    TextView rightText;
    @Bind(R.id.toolbar_divider)
    View toolbarDivider;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_refresh)
    PtrClassicFrameLayout ptrRefresh;

    ArrayList dataList;
    ShelvesBookAdapter shelvesBookAdapter;
    ShelvesFavouriteWindow favouriteWindow;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;
    private Book header;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shelves, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        //init window
        favouriteWindow = new ShelvesFavouriteWindow(getActivity());
        //        初始化刷新
        setRefresh();
        dataList = new ArrayList();
        //addHeader
//        ===========
        header = new Book();
        header.isBookShelvesFavourite = true;
        dataList.add(header);
//        ===========

        shelvesBookAdapter = new ShelvesBookAdapter(this,dataList);
        shelvesBookAdapter.setBookLongClickListener(this);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(shelvesBookAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        //setLayoutManager
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        manager.setSpanSizeLookup(new HeaderSpanSizeLookup((HeaderAndFooterRecyclerViewAdapter) recyclerView.getAdapter(), manager.getSpanCount()));
        recyclerView.setLayoutManager(manager);
        recyclerView.addOnScrollListener(mOnScrollListener);

        backInToolbar.setVisibility(View.GONE);
        leftText.setVisibility(View.VISIBLE);
        rightText.setVisibility(View.GONE);
        leftText.setText(getString(R.string.new_build));
        rightText.setText(getString(R.string.go_discover));
        leftText.setOnClickListener(this);
        rightText.setOnClickListener(this);

    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView);
            if(state == LoadingFooter.State.Loading) {
                LogUtils.kLog().e("the state is Loading, just wait..");
                return;
            }

            if (hasMore) {
                // loading more
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                loadData(mPage);
            } else {
                //the end
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                return canbePullDown;
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        BookListResponse resp = (BookListResponse) response;
        if (isNew) {
            shelvesBookAdapter.clear();
            dataList.add(header);
        }
        shelvesBookAdapter.append(resp.data.books);
        shelvesBookAdapter.notifyDataSetChanged();
    }

    @Override
    protected void showEmptyView() {

    }

    @Override
    protected void hideEmptyView() {

    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, BookListResponse.class);
    }

    @Override
    protected String cacheKey() {
        return "shelves_book";
    }

//Load and Refresh


    @Override
    public void refresh() {
        super.refresh();
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        },2000);
        onRefresh();
    }

    public void onRefresh() {
        mPage=1;
        loadData(1);
    }

    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
            loadData(mPage);
        }
    };


    protected void loadData(final int page) {
        if (!NetworkUtils.isNetAvailable(getActivity())){
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        }else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Loading);
            new RequestServerTask<BookListResponse>(BookListResponse.class) {
                @Override
                protected String requestServer() {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("userId",Global.currentUser.uid);
                    params.put("page", String.valueOf(page));
                    params.put("pageSize",10);
                    LogUtils.kLog().e("" + page);
                    return HttpUtil.post(API.GET_MY_BOOKSHELVES_OF_BOOKS, params);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    endRefreshing();
                }

                @Override
                protected void onSuccess(BookListResponse result) {
                    //没有更多数据 不能加载更多
                    if (result.data == null ||result.data.books==null|| result.data.books.length == 0) {
                        hasMore = false;
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
                    } else {
                        RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                        hasMore = true;
                        mPage++;
                        bindData(result, page == 1);
                    }
                }
            }.start();
        }
    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh!=null) {
                        ptrRefresh.refreshComplete();
                    }
                }
            }, 500);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.book_img:
                Utils.showToast(R.string.my_favourite_digest);
                break;
            case R.id.left_text:
                intent = new Intent(getActivity(), NewDigestActivity.class);
                startActivity(intent);
                break;
            case R.id.right_text:
                intent = new Intent(Constants.ACTION_MAIN_SWITCH);
                intent.putExtra(Constants.EXTRA_SWITCH_INDEX,0);
                EventBus.getDefault().post(intent);
                break;
        }
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction()==Constants.ACTION_SHELVES_FAVOURITE){
            favouriteWindow.init();
            favouriteWindow.showFavouriteWindow(recyclerView,100);
        }else if (intent.getAction()==Constants.ACTION_BOOKSHELVES_REFRESH
                ||intent.getAction()==Constants.ACTION_ADD_DIGEST_COMPLETE){
            refresh();
        }

    }



    @Override
    public void onBookLongClick(View view,final Book book) {
        ColorDialog dialog = new ColorDialog(getActivity());
        dialog.setTitle(getString(R.string.delete_this_book));
        dialog.setContentText(getString(R.string.positive_to_delete));
        dialog.setPositiveListener(getString(R.string.ok), new ColorDialog.OnPositiveListener() {
            @Override
            public void onClick(ColorDialog dialog) {
                dialog.dismiss();
                new RequestServerTask<BaseResponse>(BaseResponse.class,getActivity(),getString(R.string.commit_pls_wait)){
                    @Override
                    protected String requestServer() {
                        Map<String,Object> params = new HashMap<String, Object>();

                        params.put("token", Global.currentUser.token);
                        params.put("excerptedBookId",book.id);

                        return HttpUtil.post(API.DELETE_BOOK_TO_SHELVES,params);
                    }

                    @Override
                    protected void onSuccess(BaseResponse result) {
                        if (result.success){
                            removeBookFromBookShelves(book.id);
                        }
                    }
                }.start();
            }
        })
                .setNegativeListener(getString(R.string.cancel), new ColorDialog.OnNegativeListener() {
                    @Override
                    public void onClick(ColorDialog dialog) {
                        dialog.dismiss();
                    }
                }).show();
    }

    private void removeBookFromBookShelves(long bookId) {
       loop: for (int i = 0; i < dataList.size(); i++) {
                if (bookId == ((Book)dataList.get(i)).id) {
                    shelvesBookAdapter.remove(i);
                    break loop;
                }
             }
    }
}
